<template>
  <el-dialog
    v-if="cropperImgShow"
    title="图片裁剪"
    :visible.sync="cropperImgShow"
    :before-close="handleClose"
    :close-on-click-modal="false"
    top="5%"
    width="1280px"
  >
    <div class="batch-cropper">
      <p>
        推荐尺寸为16:9、4:3、6:7 的横版/竖版封面，展示封面大小不超过 20MB
      </p>
      <!-- 裁剪区域 -->
      <div v-if="imgSrc" class="cropper-area">
        <vue-cropper
          ref="cropper"
          :img="imgSrc"
          :outputSize="1"
          :outputType="'png'"
          :autoCrop="true"
          :autoCropWidth="autoCropWidth"
          :autoCropHeight="autoCropHeight"
          :fixed="true"
          :fixedNumber="fixedNumberName"
          style="width: 1240px; height: 900px;"
          :check-img-out-of-bound="true"
        ></vue-cropper>

        <div class="cropper-controls">
          <button @click="cropCurrent">
            裁剪当前图片
          </button>
          <button
            :class="scaleShow == item.id ? 'scaleBtn' : ''"
            v-for="(item, index) in scaleList"
            @click="scaleClick(item)"
          >
            {{ item.name }}
          </button>
        </div>
      </div>

      <!-- 结果展示 -->
      <div v-if="croppedImages.length" class="results">
        <h3>裁剪结果</h3>
        <div class="result-grid">
          <div
            v-for="(result, index) in croppedImages"
            :key="index"
            class="result-item"
          >
            <img :src="result.url" alt="" />
            <button @click="downloadImage(result, index)">下载</button>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      processFile: null,
      dialogShow: false,
      imgSrc: "",
      fixedNumberName: [16, 9],
      imageList: [],
      scaleShow: "1",
      autoCropWidth: 480,
      autoCropHeight: 200,
      imgWidth: 200,
      imgHeight: 300,
      scaleList: [
        {
          id: "1",
          name: "16:9",
          fixedNumber: [16, 9]
        },
        {
          id: "2",
          name: " 4:3",
          fixedNumber: [4, 3]
        },
        // {
        //   id: "3",
        //   name: "9:16",
        //   fixedNumber: [9, 16]
        // },
        {
          id: "4",
          name: "6:7",
          fixedNumber: [6, 7]
        }
      ],
      currentIndex: 0,
      croppedImages: []
    };
  },
  props: {
    cropperImgShow: false
  },
  watch: {
    cropperImgShow(e) {}
  },
  computed: {
    currentImage() {
      return this.imageList[this.currentIndex] || null;
    }
  },
  mounted() {},
  methods: {
    scaleClick(item) {
      this.scaleShow = item.id;
      this.fixedNumberName = item.fixedNumber;
      if(this.imgWidth<this.imgHeight){//竖图截取比例
        this.autoCropHeight = (this.autoCropWidth * item.fixedNumber[1]) / item.fixedNumber[0];
      }
      else{//横图比例
        this.autoCropWidth =(this.autoCropHeight * item.fixedNumber[0]) / item.fixedNumber[1];
        console.log(this.autoCropWidth,'???????')
      }
      
    },
    selectFiles() {
      this.$refs.fileInput.click();
    },

    handleFileSelect(e) {
      this.processFiles(e.target.files);
    },

    handleDrop(e) {
      e.preventDefault();
      this.processFiles(e.dataTransfer.files);
    },

    processFiles(file) {
      this.processFile = file;
      this.imageList = [];
      this.croppedImages = [];

      //   Array.from(files).forEach(file => {
      if (file.raw.type.startsWith("image/")) {
        const reader = new FileReader();
        reader.onload = e => {
          this.imageList.push({
            file: file.raw,
            src: e.target.result,
            preview: e.target.result,
            cropped: false
          });
          const img = new Image();
          img.onload = () => {
            this.imgSrc = e.target.result;
              console.log(img.width,img.height)
              this.imgWidth = img.width;
              this.imgHeight = img.height;
              // this.autoCropHeight=img.Height
            if(img.height>900&&img.height>img.width){//超出剪辑框高度的竖图
              this.autoCropWidth = img.width/(img.height/900);
            }else if(img.height>img.width){//未超出剪辑框高度的竖图
                this.autoCropWidth=img.width
            }

            if(img.width>1240&&img.height<img.width){//超出剪辑框高度的横图
              this.autoCropHeight = img.height/(img.width/1240);
              this.autoCropWidth =(this.autoCropHeight * 16) / 9;
            }else if(img.width>img.height){//
              this.autoCropHeight=img.height;
              this.autoCropWidth = img.width;
            }
         
            
          };
          img.src = e.target.result;
        };

        reader.readAsDataURL(file.raw);
      }
      //   });
    },

    selectImage(index) {
      this.currentIndex = index;
    },

    cropCurrent() {
      this.croppedImages = [];
      this.$refs.cropper.getCropData(data => {
        this.croppedImages.push({
          url: data,
          originalIndex: this.currentIndex
        });
        const fileName = "example.png";
        const file = this.dataURLtoFile(data, fileName);
        this.processFile.name = this.processFile.uid.toString() + ".png";
        this.processFile.width = this.$refs.cropper.cropW;
        this.processFile.height = this.$refs.cropper.cropH;
        this.processFile.raw = file;
        console.log(this.processFile); // 输出File对象
        this.$emit("cosUploadFile", this.processFile);
        this.handleClose();
        this.imageList[this.currentIndex].cropped = true;
      });
    },
    dataURLtoFile(dataurl, filename) {
      const arr = dataurl.split(",");
      const mime = arr[0].match(/:(.*?);/)[1]; // 提取MIME类型
      const bstr = atob(arr[1]); // base64解码
      let n = bstr.length;
      const u8arr = new Uint8Array(n); // 创建Uint8Array
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime }); // 创建File对象并返回
    },

    downloadImage(result, index) {
      const link = document.createElement("a");
      link.href = result.url;
      link.download = `cropped-image-${index + 1}.jpg`;
      link.click();
    },
    handleClose() {
      this.imgSrc = "";
      this.$emit("handleClose", false);
    }
  }
};
</script>

<style lang="scss" scoped>
.upload-area {
  border: 2px dashed #ccc;
  padding: 40px;
  text-align: center;
  margin-bottom: 20px;
  border-radius: 8px;
}

.upload-area:hover {
  border-color: #007bff;
}

.image-list {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  overflow-x: auto;
}

.image-item {
  position: relative;
  width: 80px;
  height: 80px;
  cursor: pointer;
  border: 2px solid transparent;
  border-radius: 4px;
}

.image-item.active {
  border-color: #007bff;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.image-status {
  position: absolute;
  top: -5px;
  right: -5px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ccc;
}

.status-success {
  color: green;
}

.cropper-controls {
  margin-top: 20px;
  text-align: center;

  button {
    margin: 0 5px;
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }

  .scaleBtn {
    background-color: #0052d9;
    color: #fff;
  }
}

.batch-btn {
  background: #28a745 !important;
  color: white;
}

.results {
  margin-top: 40px;
}

.result-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.result-item {
  text-align: center;
}

.result-item img {
  width: 100%;
  border-radius: 4px;
  border: 1px solid #ddd;
}
</style>
